<template>
    <view class="family-page" :style="{ paddingTop: vuex_custom_bar_height + 'px' }">
        <tn-nav-bar fixed backgroundColor="tn-main-gradient-orangeyellow">
            家人
            <template slot="right">
                <view class="tn-flex tn-flex-row-center tn-margin-right" @click="handleAdd">



                    添加

                </view>
            </template>
        </tn-nav-bar>

        <!-- 家人列表 -->
        <view class="family-list">
            <view v-for="member in familyMembers" :key="member.id" class="family-item">
                <text>{{ member.name }}</text>
                <view class="more-options" @tap="showActionSheet(member)">
                    <view class="dot"></view>
                    <view class="dot"></view>
                    <view class="dot"></view>
                </view>
            </view>
            <tn-empty mode="data" v-if="familyMembers.length == 0"></tn-empty>
        </view>
        <tn-popup v-model="show" mode="bottom" length="50%" :marginTop="vuex_custom_bar_height || '0px'"
            backgroundColor="#FFFFFF" :width="width" :height="height" :borderRadius="borderRadius" :closeBtn="closeBtn"
            :closeBtnIcon="closeBtnIcon" :closeBtnPosition="closeBtnPosition" :maskCloseable="maskCloseable"
            @close="handleClose">

            <view class="popup-content">
                <!-- 标题栏 -->
                <view class="popup-header">
                    <text class="popup-title">{{ isAddMode ? '添加家人信息' : '修改家人信息' }}</text>
                </view>

                <!-- 表单内容 -->
                <view class="form-item">
                    <text class="label">关系</text>
                    <input v-model="formData.relationship" placeholder="请输入关系" class="popup-input" />
                    <text v-if="errors.relationship" class="error-message">{{ errors.relationship }}</text>

                </view>

                <view class="form-item">
                    <text class="label">邮箱</text>
                    <input v-model="formData.email" placeholder="请输入邮箱" class="popup-input" />
                    <text v-if="errors.email" class="error-message">{{ errors.email }}</text>
                </view>
                <!-- 底部按钮 -->
                <view class="form-actions">
                    <tn-button @click="show = false" backgroundColor="#F5F5F5" fontColor="#333333"
                        class="cancel-btn">取消</tn-button>
                    <tn-button @click="saveFormData" backgroundColor="tn-main-gradient-orangeyellow"
                        class="save-btn">保存</tn-button>
                </view>
            </view>
        </tn-popup>
        <tn-modal v-model="modalShow" :title="title" :content="content" :button="button" @click="clickBtn"></tn-modal>
    </view>
</template>

<script>
import { family, setFamily, delFamily } from '@/api/family'
export default {
    data() {
        return {
            familyMembers: [],
            show: false,
            selectShow: false,
            mode: 'bottom',
            backgroundColor: '',
            width: '80%',
            height: '50%',
            borderRadius: 23,
            closeBtn: true,
            closeBtnIcon: '',
            closeBtnPosition: 'top-right',
            maskCloseable: true,
            isAddMode: true,
            formData: {
                relationship: '',
                email: ''
            },
            errors: {
                relationship: '',
                email: ''
            },
            modalShow: false,
            title: '提示',
            content: '确定要删除吗？',
            button: [
                {
                    text: '取消',
                    backgroundColor: '#A4E82F',
                    fontColor: '#FFFFFF'
                },
                {
                    text: '确定',
                    backgroundColor: 'tn-bg-indigo',
                    fontColor: '#FFFFFF'
                }
            ],
            delMemberId: ''
        };
    },
    onLoad() {
        this.getData()
    },
    methods: {
        handleAdd() {
            // 处理添加逻辑
            this.formData = {
                relationship: '',
                email: ''
            }
            this.show = true
            this.isAddMode = true
        },
        handleCancel() {
            uni.navigateBack();
        },
        showActionSheet(member) {
            uni.showActionSheet({
                itemList: ['修改', '删除'],
                success: (res) => {
                    if (res.tapIndex === 0) {
                        this.handleModify(member);
                    } else if (res.tapIndex === 1) {
                        this.handleDelete(member);
                    }
                }
            });
        },
        handleModify(member) {
            const { id } = member;
            const { name: relationship, email } = this.familyMembers.find(item => item.id === id) || {};
            this.formData = { id, relationship, email };
            Object.assign(this, {
                isAddMode: false,
                show: true
            });
        },
        handleDelete(member) {
            this.modalShow = true;
            this.delMemberId = member.id
        },
        handleClose() {
            this.show = false
        },
        async saveFormData() {
            if (!this.validateFormData()) return;
            const familyData = {
                name: this.formData.relationship,
                email: this.formData.email,
                ...(this.formData.id && { id: this.formData.id })
            }
            try {
                await setFamily(familyData);
                const toastConfig = {
                    duration: 2000,
                    title: '保存成功',
                    icon: 'success'
                };
                uni.showToast(toastConfig);
                this.getData()


            } catch (error) {
                console.error('Failed to set family:', error);
                toastConfig.title = '保存失败';
                toastConfig.icon = 'error';
                uni.showToast(toastConfig);
            }
            this.show = false;
        },

        validateFormData() {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            let isValid = true;

            if (this.formData.relationship.trim() === '') {
                this.errors.relationship = '关系不能为空';
                isValid = false;
            } else {
                this.errors.relationship = '';
            }

            if (!emailRegex.test(this.formData.email.trim())) {
                this.errors.email = '请输入有效的邮箱地址';
                isValid = false;
            } else {
                this.errors.email = '';
            }

            return isValid;
        },
        clickBtn(e) {
            if (e.index === 1) {
                delFamily({ id: this.delMemberId }).then(res => {
                    this.familyMembers = this.familyMembers.filter(m => m.id !== this.delMemberId);
                    uni.showToast({
                        title: '删除成功',
                        icon: 'none'
                    });
                }).catch(err => {
                    console.log(err)
                });
            }
            this.modalShow = false
        },
        getData() {
            family().then(res => {
                this.familyMembers = res
            }).catch(err => {
                console.log(err)
            })
        }
    }
};
</script>

<style lang="scss" scoped>
.family-page {
    padding: 0;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.tn-nav-bar {
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.tn-button {
    font-size: 14px;
    padding: 6px 16px;
    transition: background-color 0.3s ease;
}

.tn-button:active {
    background-color: rgba(255, 255, 255, 0.2);
}

.family-list {
    background-color: #fff;
    margin: 0;
    margin-top: 20px;
}

.family-item {
    padding: 15px 20px;
    border-bottom: 1px solid #eee;
    display: flex;
    align-items: center;
    justify-content: space-between;
    transition: background-color 0.3s ease;

    &:last-child {
        border-bottom: none;
    }

    &:active {
        background-color: #f8f8f8;
    }

    text {
        font-size: 16px;
        color: #333;
    }
}

.more-options {
    display: flex;
    align-items: center;
    gap: 6rpx;
    padding: 4rpx 8rpx;
    
    .dot {
        width: 8rpx;
        height: 8rpx;
        border-radius: 50%;
        background-color: #999;
    }
}

.popup-content {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    min-height: 100%;
    padding: 30rpx;

    .popup-header {
        text-align: center;

        .popup-title {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
        }
    }

    .form-item {
        margin-bottom: 20rpx;

        .label {
            display: block;
            font-size: 28rpx;
            color: #333;
            margin-bottom: 10rpx;
        }

        .popup-input {
            background-color: #F4F4F4;
            height: 40px;
            flex: 1;
            box-sizing: border-box;
            border-radius: 4px;
            font-size: 16px;
        }

        .error-message {
            color: red;
            font-size: 24rpx;
            margin-top: 5rpx;
        }
    }

    .form-actions {
        display: flex;
        gap: 15rpx;
        margin-top: 20rpx;

        .cancel-btn,
        .save-btn {
            flex: 1;
            height: 80rpx;
            border-radius: 12rpx;

            &::after {
                border: none;
            }
        }
    }
}
</style>